import { StyleValue } from 'vue'
import { Autosize } from './inputProps'

export function calcTextareaHeight(el: HTMLInputElement | HTMLTextAreaElement, autosize: Autosize) {
  if (!el) return

  if (autosize == false) {
    return { height: 'unset' }
  }

  el.style.height = '' // 刷新scrollHeight

  // @ts-ignore
  const { minRows = 3, maxRows } = autosize
  const style: StyleValue = {}

  let minHeight = 0,
    maxHeight = Number.MAX_SAFE_INTEGER,
    height = el.scrollHeight

  const lh = parseInt(window.getComputedStyle(el).lineHeight)

  if (minRows > 0) {
    minHeight = minRows * lh
    style.minHeight = minHeight + 'px'
  }
  if (maxRows > 0) {
    maxHeight = maxRows * lh
    style.maxHeight = maxHeight + 'px'
  }

  style.height = Math.min(maxHeight, Math.max(minHeight, height)) + 'px'

  return style
}
